/*
 * =====================================================================================
 *
 *       Filename:  CodeDetector.cpp
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  2015年03月28日 15时13分03秒
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  LiuYi (), swliuyi@gmail.com
 *   Organization:  
 *
 * =====================================================================================
 */
#include "CodeDetector.h"

using namespace std;
string CodeDetector::CodeDetect(string path)
{

    char buffer[65535];
    FILE * fp = stdin;
    fp = fopen(path.c_str(), "r");
    if (fp == NULL)
    {
        cerr<<"Cannot open file"<<endl;
        return "";
    }
    uchardet_t handle = uchardet_new();
    while (!feof(fp))
    {
        size_t len = fread(buffer, 1, m_bufferSize, fp);
        int retval = uchardet_handle_data(handle, buffer, len);
        if (retval != 0)
        {
            fprintf(stderr, "Handle data error.\n");
            cerr<<"Handle data error"<<endl;
            return "";
        }
    }
    uchardet_data_end(handle);
    const char * charset = uchardet_get_charset(handle);
    string res(charset);
    if (*charset)
      return res;
    else
      return "ascii";
    uchardet_delete(handle);
}
